package com.xxxx.server.controller;

import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.Employee;
import com.xxxx.server.pojo.Msg;
import com.xxxx.server.rest.RespBean;
import com.xxxx.server.service.AmqpService;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.utils.GetAdminUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author : ymd
 * @Date : 2020/10/16 0016 16:22
 * @Version 1.0
 * @Description : 聊天接口
 */
@Api("在线聊天")
@Controller
public class ChatController {
    @Resource
    private IAdminService adminService;
    @Resource
    private AmqpService amqpService;
    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;
    /**
     * 查询聊天人员列表接口
     * @return
     */
    @ApiOperation(value = "查询聊天人员列表")
    @GetMapping("/chat/admin")
    @ResponseBody
    public List<Admin> getChatAdmin(){
        //查询当前用户
        final Admin currentAdmin = GetAdminUtils.getAdmin();
        //设置密码为空
        currentAdmin.setPassword(null);
        //查询所有用户并移除自己
        final List<Admin> admins = adminService.selectAdminList("");
        Admin adminTemp=null;
        for (Admin admin : admins){
            if (admin.getId()==currentAdmin.getId()){
                adminTemp=admin;
            }
            admin.setRoles(adminService.getRoles(admin.getId()));
        }
        admins.remove(adminTemp);
        return admins;
    }

    /**
     * 聊天接口
     */
    @MessageMapping("/ws/chat")
    public void handleMessage (Authentication authentication, Msg msg){
        //设置Msg对象
        Admin admin = (Admin)authentication.getPrincipal();
        msg.setFrom(admin.getUsername());
        msg.setFromName(admin.getName());
        msg.setTime(LocalDateTime.now());
        //发消息给指定的用户
        //指定用户名   前台发送的队列    服务器应该发送的消息
        simpMessagingTemplate.convertAndSendToUser(msg.getTo(), "/queue/chat",msg);
    }

    @ApiOperation(value = "发邮件、短信")
    @GetMapping("/amq1")
    @ResponseBody
    public RespBean amqp (Employee employee){
        amqpService.handler(employee);
        return RespBean.success("OK!");
    }
}
